package edu.nf.supermarket.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.nf.supermarket.result.ResultVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yjj
 * @date 2025-05-20
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 设置 CORS 响应头
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "token, content-type, authorization");
        response.setHeader("Access-Control-Max-Age", "3600");

        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }

        System.out.println("登录拦截器");
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        //获取token认证
        String token = request.getHeader("token");
        if (token != null) {
            return true;
        } else {
            ResultVO<String> vo = new ResultVO<>();
            vo.setCode(HttpStatus.UNAUTHORIZED.value());
            vo.setMessage("请先登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(vo));
            return false;

        }
    }
}
